<template>
  <div class="index">
    <Header></Header>
    <div class="main">
      <p class="current-nav">
        当前位置 :
        <router-link to="index">首页</router-link>
        <i>></i>
        <a>风险评估及资源调查</a>
        <i>></i>风险信息
      </p>

      <div class="infor risk">
        <!-- <p class="title">风险信息</p> -->
        <ul class="clearfix steps" style="margin-top:30px;">
          <li class="steps-active" @click="goToPage(0)">
            <span>1</span>
            <p>风险信息</p>
            <p class="info_note clearfix">
              <i class="el-icon-warning-outline"></i>
              <span
              >请录入单位涉及的全部风险信息再进入下一步，否则可能导致推荐的应急预案不完整！</span
              >
            </p>
          </li>
          <li @click="goToPage(1)">
            <span>2</span>
            <p style="margin-left:-13px;">应急资源信息</p>
            <p class="info_note clearfix">
              <i class="el-icon-warning-outline"></i>
              <span
              >请正确填写应急资源信息，该信息会自动更新到应急预案中！</span
              >
            </p>
          </li>
          <!-- <li>
              <span>3</span>
              <p>报告信息</p>
              <p class="info_note clearfix">
                  <i class="el-icon-warning-outline"></i>
                  <span>请正确填写单位基本信息，该信息会自动更新到对应的应急预案中！</span>
              </p>
          </li> -->
        </ul>
        <div class="form-container">
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline"
          >
            <el-form-item label>
              <el-select
                v-model="region"
                placeholder="突发事件分类"
                @change="selecttwo"
              >
                <el-option
                  v-for="(item, index) in levelfirst"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
              <el-select
                placeholder="突发事件"
                v-model="region1"
                @change="selectthree"
              >
                <el-option
                  v-for="(item, index) in leveltwo"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
              <el-select v-model="region2" placeholder="具体事故">
                <el-option
                  v-for="(item, index) in levelthree"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <!--<el-form-item label="">
        <el-input v-model="inputUserperson"></el-input>
            </el-form-item>-->
            <el-form-item>
              <el-button
                @click="lookrisk"
                class="sure"
                style="text-align:center"
              >
                <i class="el-icon-search"></i> 搜索
              </el-button>
              <el-button
                @click="reserve"
                class="sure"
                style="text-align:center"
              >
                <!--<img src="../../../static/images/search.png" />-->
                <i class="el-icon-refresh"></i>
                重置
              </el-button>
            </el-form-item>
          </el-form>
          <div class="risk-title">
            <p>风险库</p>
            <div>
              <div class="selectL">
                已选个数（
                <span>{{ selectNumber }}</span
                >）
              </div>
              <el-button v-loading @click="reservedemo">
                <i class="el-icon-refresh-right">刷新</i>
              </el-button>
              <el-button @click="downloadmsg">
                <i class="el-icon-download">下载</i>
              </el-button>
            </div>
          </div>
          <el-table
            ref="multipleTable"
            :data="riskList"
            tooltip-effect="light"
            @selection-change="handleSelectionChange"
            :row-key="getRowKeys"
            v-loading.lock="loading"
            element-loading-spinner="el-icon-loading"
          >
            <el-table-column
              type="index"
              align="center"
              label="序号"
            >
              <template slot-scope="scope">{{
                (pageIndex - 1) * pageSize + scope.$index + 1
                }}
              </template>
            </el-table-column>
            <el-table-column
              label
              :reserve-selection="true"
              type="selection"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="emergenciesTypeName"
              label="突发事件分类"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="dangerSourceName"
              label="突发事件"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="accidentTypeName"
              label="具体事故(设备故障)"
              align="center"
            >
              <template slot-scope="scope">{{
                scope.row.accidentTypeName
                ? scope.row.accidentTypeName
                : "/"
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="riskDesc"
              label="风险"
              align="center"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              label="操作"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-button
                  class="detail-btn"
                  @click="editList(scope.row)"
                ><i class="el-icon-edit">修改</i></el-button
                >
                <el-button
                  class="detail-btn"
                  @click="deleteList(scope.row,'2')"
                ><i class="el-icon-delete"
                >删除</i
                ></el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="page-container">
            <el-pagination
              @current-change="lookrisk"
              :current-page.sync="pageIndex"
              @size-change="handleSizeChange"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
         <!--   <el-pagination
              @current-change="lookrisk"
              :current-page.sync="pageIndex"
              :page-size="pageSize"
              layout="total, prev, pager, next, jumper"
              :total="total"
            ></el-pagination>-->
            <el-button>确定</el-button>
          </div>
          <div class="risk-title">
            <p>删除的风险信息</p>
          </div>
          <el-table
            :data="riskList1"
            tooltip-effect="light"
            :row-key="getRowKeys"
            v-loading.lock="loading"
            element-loading-spinner="el-icon-loading"
          >
            <el-table-column
              type="index"
              align="center"
              label="序号"
            >
              <template slot-scope="scope">{{
                (pageIndex - 1) * pageSize + scope.$index + 1
                }}
              </template>
            </el-table-column>
            <!--     <el-table-column
                   label
                   :reserve-selection="true"
                   type="selection"
                   align="center"
                 ></el-table-column>-->
            <el-table-column
              prop="emergenciesTypeName"
              label="突发事件分类"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="dangerSourceName"
              label="突发事件"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="accidentTypeName"
              label="具体事故(设备故障)"
              align="center"
            >
              <template slot-scope="scope">{{
                scope.row.accidentTypeName
                ? scope.row.accidentTypeName
                : "/"
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="riskDesc"
              label="风险"
              align="center"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              label="操作"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-button
                  class="detail-btn"
                  @click="deleteList(scope.row,'1')"
                ><i class="el-icon-refresh-right"
                >还原</i
                ></el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="page-container">
            <el-pagination
              @current-change="lookrisk1"
              :current-page.sync="pageIndex1"
              @size-change="handleSizeChange1"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total1"
            ></el-pagination>
            <el-button>确定</el-button>
          </div>
          <div class="bts" style="margin:0 auto;width:136px;">
            <!--<el-button @click="resetForm('ruleForm')" class='cancel'>保存</el-button>-->
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
              class="sure surell"
            >下一步
            </el-button
            >
          </div>
          <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%"
          >
            <el-input
              type="textarea"
              rows="10"
              v-model="editValue"
            ></el-input>

            <span slot="footer" class="dialog-footer">
                            <el-button @click="dialogVisible = false"
                            >取 消</el-button
                            >
                            <el-button type="primary" @click="dorightchange"
                            >确 定</el-button
                            >
                        </span>
          </el-dialog>
        </div>
      </div>
    </div>
    <Footer/>
  </div>
</template>

<script>
  import Header from "../common/header";
  import Footer from "../common/footer";

  export default {
    components: {
      Header,
      Footer
    },
    data() {
      return {
        formInline: {
          user: "",
          region: ""
        },
        dialogVisible: false,
        editValue: "修改",
        multipleSelection: [],
        currentPage: 1,
        pageIndex: 1,
        pageSize: 10,
        currentPage1: 1,
        pageIndex1: 1,
        pageSize1: 10,
        searchType: 2,
        total: 0,
        total1: 0,

        levelfirst: [],
        leveltwo: [],
        levelthree: [],
        dataList: [],
        riskList: [],
        riskList1: [],
        region: "",
        region1: "",
        region2: "",
        inputUserperson: "",

        saveList: "",

        accidentTypeId: "", //事故类型id
        dangerSourceId: "",
        emergenciesTypeId: "",

        selectList: [],
        selectNumber: 0,
        modifyId: "",
        navChildren: []
      };
    },
    created() {
      this.navChildren = JSON.parse(this.$route.query.navChildren)
      this.getList();
      this.lookrisk("first");
      this.lookrisk1();
      this.loading = true;
      // this.createBeforeunloadHandler()
    },
    methods: {
      goToPage(index) {
        this.$router.push({
          path: this.navChildren[index].menuUrl,
          query: {
            navIndex: this.$route.query.navIndex,
            navChildren: this.$route.query.navChildren
          }
        })
      },
      handleSizeChange(val) {
        this.pageSize=val
        this.lookrisk()
      },
      handleSizeChange1(val) {
        this.pageSize1=val
        this.lookrisk1()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
      submitForm() {
        let arr = [];
        this.multipleSelection = [
          ...this.multipleSelection,
          ...this.selectList
        ];
        window.localStorage.setItem(
          "newList",
          JSON.stringify(this.multipleSelection)
        );
        this.multipleSelection.forEach(item => {
          arr = [...arr, item.riskId];
        });
        let riskIds = arr.join(",");
        let params = {
          companyId: JSON.parse(localStorage.getItem("user")).companyId,
          riskIds: riskIds
        };

        if (this.selectNumber >= 2) {
          //  window.localStorage.setItem("")
          this.$router.push({
            path: "/resources",
            query: {
              riskIds: riskIds,
              navIndex: this.$route.query.navIndex,
              navChildren: this.$route.query.navChildren
            }
          });
          // console.log(111)
        } else {
          this.$message({
            message: "请选择至少所需的两条风险库",
            type: "error"
          });
          return false
        }

        this.$axios
        ({
          method: 'post',
          url: this.$baseUrl + "emergency/v1.0/selected/risk/save",
          data: params
        }).then(
          (res) => {
            let data = res.data.meta;
            if (data.success) {
              this.$router.push({
                path: 'resources',
                query: {
                  navIndex: this.$route.query.navIndex,
                  navChildren: this.$route.query.navChildren
                }
              })
            } else {
              // this.$message({
              //   message: res.data.meta.message,
              //   type: 'error'
              // });
              console.log(res.data.meta.message)
            }
          }
        )
        // this.$router.push({path:'resources',query:{navIndex:1}})
      },
      onSubmit() {
        console.log("submit!");
      },
      getRowKeys(row) {
        return row.riskId;
      },
      // toggleSelection(rows,selected) {
      // 	if(rows) {
      // 		rows.forEach(row => {
      // 			this.$refs.multipleTable.toggleRowSelection(row,selected);
      // 		});
      // 	} else {
      // 		this.$refs.multipleTable.clearSelection();
      // 	}
      // },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.$store.state.riskList = val;

        this.selectNumber =
          this.selectList.length + this.multipleSelection.length;
        window.localStorage.setItem(
          "newList",
          JSON.stringify(this.multipleSelection)
        );
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      getList() {
        //  let params ={
        //     pageIndex: this.pageIndex,
        //     pageSize: this.pageSize,
        //     searchType: this.searchType
        //  }
        this.$axios({
          method: "post",
          url: this.$baseUrl + "emergency/v1.0/risk/tree",
          data: {}
        }).then(res => {
          this.dataList = res.data.data;
          console.log(this.dataList);
          //  = [this.dataList];

          if (this.dataList.children) {
            this.levelfirst = this.dataList.children;
          }
        });
      },
      selecttwo(id) {
        this.levelfirst.map(item => {
          if (item.id == id) {
            if (item.children) {
              this.leveltwo = item.children;
              this.region1 = "";
              this.region2 = "";
              this.levelthree = [];
            }
          }
        });
      },
      selectthree(id) {
        // this.formInline.region2 = "";
        if (this.dataList.children) {
          this.leveltwo.map(item => {
            if (item.id == id) {
              if (item.children) {
                this.levelthree = item.children;
                this.region2 = "";
              }
            }
          });
        }
      },
      lookrisk(flag) {
        let params = {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          companyId: JSON.parse(localStorage.getItem("user")).companyId,
          emergenciesTypeId: this.region,
          dangerSourceId: this.region1,
          accidentTypeId: this.region2, //事故类型id
          isValid: '1',
        };
        this.$axios({
          method: "post",
          url: this.$baseUrl + "emergency/v1.0/risk/list",
          data: params
        }).then(res => {
          this.loading = false;
          let data = res.data.meta;
          if (data.success) {
            this.riskList = res.data.data.records;
            this.total = res.data.data.total;
            if (flag == "first") {
              let arr;
              if (
                window.localStorage.getItem("newList") ||
                localStorage.getItem("newList")
              ) {
                arr =
                  JSON.parse(window.localStorage.newList) ||
                  JSON.parse(localStorage.getItem("newList"));
              }
              let crr = [];
              this.selectList = [...arr];
              let numberindex = [];
              arr.forEach((row, deindex) => {
                this.riskList.forEach((item, index) => {
                  if (row.riskId == item.riskId) {
                    crr = [...crr, item];
                    numberindex = [...numberindex, deindex];
                    console.log(this.selectList);
                    this.selectList[deindex] = "";
                  }
                });
              });
              for (var i = 0; i < this.selectList.length; i++) {
                if (
                  this.selectList[i] == "" ||
                  this.selectList[i] == null ||
                  typeof this.selectList[i] == undefined
                ) {
                  this.selectList.splice(i, 1);
                  i = i - 1;
                }
              }
              this.$nextTick(() => {
                crr.forEach(row => {
                  this.$refs.multipleTable.toggleRowSelection(
                    row,
                    true
                  );
                });
              });
              // this.selectNumber = this.selectList.length+this.multipleSelection.length;
            } else {
              let arr = [];
              arr = [...this.selectList];
              // this.multipleSelection = [...this.selectList,this.multipleSelection]
              // window.localStorage.setItem("newList",JSON.stringify(this.multipleSelection))
              let crr = [];
              arr.forEach((row, deindex) => {
                this.riskList.forEach((item, index) => {
                  if (row.riskId == item.riskId) {
                    crr = [...crr, item];
                    this.selectList[deindex] = "";
                  }
                });
              });
              for (var i = 0; i < this.selectList.length; i++) {
                if (
                  this.selectList[i] == "" ||
                  this.selectList[i] == null ||
                  typeof this.selectList[i] == undefined
                ) {
                  this.selectList.splice(i, 1);
                  i = i - 1;
                }
              }
              this.$nextTick(() => {
                crr.forEach(row => {
                  this.$refs.multipleTable.toggleRowSelection(
                    row,
                    true
                  );
                  debugger;
                });
              });
            }
            if (flag == "two") {
              this.$message({
                message: "刷新成功",
                type: "success"
              });
            }
          } else {
            this.riskList = [];
            this.$message({
              message: data.message,
              type: "error"
            });
          }
        });
      },
      lookrisk1() {
        let params = {
          pageIndex: this.pageIndex1,
          pageSize: this.pageSize1,
          companyId: JSON.parse(localStorage.getItem("user")).companyId,
          isValid: '2',
          /*      emergenciesTypeId: this.region,
                dangerSourceId: this.region1,
                accidentTypeId: this.region2 //事故类型id*/
        };
        this.$axios({
          method: "post",
          url: this.$baseUrl + "emergency/v1.0/risk/list",
          data: params
        }).then(res => {
          this.loading = false;
          let data = res.data.meta;
          if (data.success) {
            this.riskList1 = res.data.data.records;
            this.total1 = res.data.data.total;
          } else {
            this.riskList1 = [];
            /*this.$message({
              message: data.message,
              type: "error"
            });*/
          }
        });
      },
      deleteList(item, num) {
        debugger
        let params = {
          companyId: JSON.parse(localStorage.getItem("user")).companyId,
          riskId: item.riskId,
          isValid: num
        };
        this.$axios({
          method: "post",
          url: this.$baseUrl + "emergency/v1.0/risk/delete",
          data: params
        }).then(res => {
          let data = res.data.meta;

          if (data.success) {
            this.$refs.multipleTable.toggleRowSelection(item, false);
            if(num==1){
              this.$message({
                message: "还原成功",
                type: "success"
              });
            }else{
              this.$message({
                message: "删除成功",
                type: "success"
              });
            }
            this.lookrisk('first');
            this.lookrisk1();
          } else {
            this.$message({
              message: res.data.meta.message,
              type: "error"
            });
          }
        });
      },
      reserve() {
        this.region = "";
        this.region1 = "";
        this.region2 = "";
        this.leveltwo = [];
        this.levelthree = [];
        this.inputUserperson = "";
        this.$refs.multipleTable.clearSelection();
        this.lookrisk("first");
      },
      editList(item) {
        this.dialogVisible = true;
        this.editValue = item.riskDesc;
        this.modifyId = item.id;
      },
      reservedemo() {
        this.pageIndex = 1;
        this.lookrisk("two");
      },
      downloadmsg() {
        let id = "";
        let arr = [];

        this.multipleSelection.forEach(item => {
          arr = [...arr, item.riskId];
        });

        //  var ajax = new XMLHttpRequest();
        //   //步骤二:设置请求的url参数,参数一是请求的类型,参数二是请求的url,可以带参数,动态的传递参数starName到服务端
        //   ajax.open('get',this.$baseUrl+"report/export?companyId="+JSON.parse(localStorage.getItem('user')).companyId+id);
        //   //步骤三:发送请求
        //   ajax.send();
        //   //步骤四:注册事件 onreadystatechange 状态改变就会调用
        //   ajax.onreadystatechange = function () {
        //     if (ajax.readyState==4 &&ajax.status==200) {
        //       //步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的
        //   　　　　console.log(ajax.responseText);//输入相应的内容
        //     　　}
        //   }
        this.$axios({
          method: "post",
          url: this.$baseUrl + "report/export",
          data: {
            companyId: JSON.parse(localStorage.getItem("user"))
              .companyId,
            riskIds: arr.join(",")
          },
          // headers:{
          // 'Content-Type':'application/x-www-form-urlencoded'
          // },
          responseType: "blob"
        }).then(res => {
          var timestamp = Date.parse(new Date());
          const content = res.data;
          const blob = new Blob([content]);
          const filename = timestamp + ".xls";
          if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = filename;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, filename);
          }
        });
      },
      dorightchange() {
        let params = {
          id: this.modifyId,
          riskDesc: this.editValue
        };
        this.$axios({
          method: "post",
          url: this.$baseUrl + "emergency/v1.0/risk/modify",
          data: params
        }).then(res => {
          if (res.data.meta.success) {
            this.dialogVisible = false;
            this.$message({
              message: "修改成功",
              type: "success"
            });
            this.lookrisk("first");
          } else {
            this.$message({
              message: res.data.meta.message,
              type: error
            });
          }
        });
      },
      createBeforeunloadHandler() {
        //window.addEventListener('beforeunload', e => this.beforeunloadHandler(e));
        window.addEventListener(
          "beforeunload",
          this.beforeunloadHandler,
          false
        );
      },
      beforeunloadHandler() {
        this.multipleSelection = [
          ...this.multipleSelection,
          ...this.selectList
        ];
        window.localStorage.setItem(
          "newList",
          JSON.stringify(this.multipleSelection)
        );
      },
      destroyedBeforeunloadHandler() {
        //window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e));//错误方法，无法移除
        window.removeEventListener(
          "beforeunload",
          this.beforeunloadHandler,
          false
        );
        //this.rowEditEnable = 0;
      }
    },
    destroyed() {
      // this.destroyedBeforeunloadHandler();
      // this.multipleSelection = [...this.multipleSelection,...this.selectList];
      // window.localStorage.setItem("newList",JSON.stringify(this.multipleSelection));
    }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less'>
  @import "../../../static/css/information.less";

  .risk {
    .form-container {
      padding: 50px 0 70px;
      margin: 0 auto;
      .el-table {
        width: calc(100% - 200px);
        margin: 0 auto;
        border-top: 1px solid #ebeef5;
      }
      .el-button:hover {
        opacity: 0.8;
      }
      .risk-title {
        position: relative;
        margin: 66px 0 25px;
        p {
          font-size: 24px;
          font-weight: 900;
          color: #333333;
          text-align: center;
        }
        > div {
          overflow: hidden;
          width: 100%;
          height: 40px;
          padding: 0 100px;
          .el-button {
            width: 80px;
            background: #f8f7ff;
            border: 0;
            border-radius: 6px;
            margin-right: 4px;
            float: right;
            font-size: 14px;
            color: #6492ff;
          }
          > .selectL {
            height: 40px;
            width: 200px;
            float: left;
            > span {
              color: #409eff;
            }
          }
        }
      }
      .el-form {
        width: 790px;
        height: 36px;
        margin: 0 auto;
        .el-input {
          width: 182px;
          margin-right: 12px;
        }
        .el-button {
          width: 80px;
          height: 36px;
          border-radius: 6px;
          padding: 0;
          color: #fff;
          text-align: left;
          img {
            width: 18px;
            margin: 0 4px 0 12px;
          }
        }
        .el-button.sure {
          color: #fff;
          background: #4080ff;
         /* background: linear-gradient(90deg, #6eb1ff 20%, #3372ff 80%);*/
        }
        .el-button.sure:hover {
          opacity: 0.8;
        }
        .el-input__inner {
          height: 36px;
          line-height: 36px;
        }
      }
    }
    .detail-btn {
      color: #4180ff;
      background: #f7f6fe;
      border: 1px solid #4180ff;
      border-radius: 8px;
      span {
        color: #4180ff;
      }
    }
  }
</style>
